<?php

/*
采购订单列表
*/
namespace Modules\Purchasing\Http\Repositories;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Modules\Purchasing\Models\Provisional;
use Modules\Purchasing\Models\Provisionalschedule;
use Illuminate\Support\Facades\DB;
use Catch\Exceptions\FailedException;
use Modules\Base\Service\BoxService;
use Modules\Purchasing\Models\Supplier;
use Modules\Purchasing\Models\Supplierschedule;
use Modules\Purchasing\Models\Purchaseorder;
use Modules\Purchasing\Models\Purchaseorderschedule;
use Modules\Warehouse\Models\Storagelocation;
use Modules\Purchasing\Models\Inspectionlist;
use Modules\Purchasing\Models\Inspectionlistcheck;
use Modules\Purchasing\Models\Purchasewarehousing;
use extend\services\warehouse\{warehouseService};//引入自定义类
use Modules\Purchasing\Models\Purchasereturn;
use Modules\Purchasing\Models\PurchasereturnAttached;
use App\Enums\InvTransDocType;
use App\Services\InventoryService;
use Modules\Purchasing\Models\PurchasewarehousingMateriel;
// use Modules\Purchasing\Models\PurchasewarehousingAtached;
use App\Services\KingDeeService;
use Modules\Inventory\Models\Inventory;
use Modules\Salesmanagement\Models\Salesreturn;
use Modules\Salesmanagement\Models\SalesreturnAttached;
use Modules\Salesmanagement\Models\SalesoutAttached;
use Modules\Salesmanagement\Models\Salesout;
use Modules\Salesmanagement\Models\SalesoutTiaoma;
use Modules\Base\Models\Material;



class PurchasereturnReget
{
   

     /*
    数据添加方法
    */
    public static function create(array $data)
    {
        
        $Purchasereturn = new Purchasereturn;
        return self::createOrSave($Purchasereturn, $data);
    }

    //数据添加方法
    public static function createOrSave(Purchasereturn $Purchasereturn,$data)
    {

        
        try {
            //开始起事务
            DB::beginTransaction();

            $Purchasewdata = [];
            // $Purchasewdata['returnnumber'] = 'CGTH'.date('Ymd',time()).makeSerial();
            $Purchasewdata['returnnumber'] =  \App\Services\UnitService::createDocno(\App\Enums\OrderNoPrefix::NO_CGTH->value);
           
            // $Purchasewdata['remarks'] = '';
            $Purchasewdata['creator_id'] = $data['creator_id'];
            $Purchasewdata['source'] = $data['source'];//判断
            $Purchasereturn->fill($Purchasewdata);
            $Purchasereturn->save();
           
            // $data['detailscheck_all'] = [
            //     [
            //         'purchaseorder_id'=>1,
            //         'purchaseorderschedule_id'=>1,
            //         'quantityreturned'=>1,
            //         'barcode'=>1,
            //         'storagelocation'=>1,
            //     ],
            //     [
            //         'purchaseorder_id'=>1,
            //         'purchaseorderschedule_id'=>1,
            //         'quantityreturned'=>1,
            //         'storagelocation'=>1,
            //         'barcode'=>1,
            //     ]
            // ];
           
            $Purchasereturn->detailscheckAll()->createMany( $data['detailscheck_all'] );

            DB::commit();
            return ['code'=>1000,'message'=>'添加成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('数据添加失败，服务器上火星了请联系技术处理');
        }
    }

    //修改
    public static function createUpdate($id,$data)
    {
        try {
            //开始起事务
            DB::beginTransaction();
          
            PurchasereturnAttached::query()->where('id',$id)->update($data); 
            DB::commit();
            return ['code'=>1000,'message'=>'修改成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('服务器飞出地球了请联系技术找回');
        }
    }

    /**
     * 查询一条数据
     *
     */
    public static function find($id)
    {
        return Provisional::query()->with('detailscheckAll')->find($id);
    }

    /**
     * @param $id
     * @return void
     */
    public static function delete($id)
    {
       
        try {
            //开始起事务
            DB::beginTransaction();
            PurchasereturnAttached::query()->where('id',$id['id'])->delete();
            Purchasereturn::query()->where('id',$id['purchasereturn_id'])->delete();
          
            DB::commit();
            return '删除成功';
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('服务器飞出地球了请联系技术找回');
        }

    }
    
     /**采购退货单审核审核
     * @param $id
     * @return void
     */
    public static function auditupdate($id)
    {
        return throw new FailedException('亲，无该条数据审核失败');
        $Model = [];
        $returnnumber = Purchasereturn::select('returnnumber','incomingtype','fbillno','source')
        ->where('id',$id)
        ->where('state',0)
        ->first();

        if(empty($returnnumber)){
           return throw new FailedException('亲，无该条数据审核失败');
        }

        //组织外
        if($returnnumber['incomingtype'] == 0 && $returnnumber['source'] == 0){

            // 更新及时库存
            // $inventory = [];
            //汇总查询 金蝶推送
            $data = PurchasereturnAttached::select(
                'purchasereturn_id',
                'purchaseorder_id',
                'purchaseorderschedule_id',
                // 'barcode',
                'storagelocation',
                'purchasewarehousing_id',
                DB::raw('SUM(quantityreturned) as quantityreturned'),
                )
            ->where('purchasereturn_id',$id)
            ->groupby(['purchasereturn_id','purchaseorder_id','purchaseorderschedule_id','storagelocation','purchasewarehousing_id'])
            ->get()
            ->toArray();
            // $kingDeeService = new warehouseService();
            // $resdata = $kingDeeService->warehousedataApiTwo();

            
            foreach($data as $k=>$v){

                $dataPurchaseorderschedule = Purchaseorderschedule::query()->select('fseq','fmaterialid','funitid_number','purchaseorder_id')
                    ->where('id',$v['purchaseorderschedule_id'])
                    ->groupby(['purchaseorder_id','fid','fseq','fmaterialid','fmaterialname','fmaterialmodel','fmodel','funitid_number'])
                    ->first();
                   $Purchaseorder = Purchaseorder::select('fbillno','fpurchaseorgid_number','fpurchaseorgid_name','fsupplierid_number')->where('id',$v['purchaseorder_id'])->first();//采购订单
                   $warehosnumber = Purchasewarehousing::select('warehosnumber')
                   ->where('id',$v['purchasewarehousing_id'])
                   ->first();
                    // $FBILLNO = Provisionalschedule::query()
                    // ->select('purchasewarehousing.warehosnumber')
                    // ->join('purchasewarehousing as purchasewarehousing', 'purchasewarehousing.id', '=', 'provisionalschedule.purchasewarehousing_id')
                    // ->where('barcode',$v['barcode'])
                    // ->first();
                    
                    if(empty($Purchaseorder)||empty($dataPurchaseorderschedule)) return throw new FailedException('采购数据查询出错');
                    $Model[$k]['FORGID'] = $Purchaseorder['fpurchaseorgid_number'];//编码
                    $Model[$k]['FSRCBILLNO'] = $warehosnumber->warehosnumber;//原单号采购入库单
                    $Model[$k]['FSRCSEQ'] = $dataPurchaseorderschedule['fseq'];//物料源单行号
                    $Model[$k]['FMATERIALID'] = $dataPurchaseorderschedule['fmaterialid']; //SKU（传编码）
                    $Model[$k]['FUNITID'] = $dataPurchaseorderschedule['funitid_number'];//单位（传编码）
                    $Model[$k]['FQTY'] = $v['quantityreturned'];
                    $Model[$k]['FOwnerTypeId'] = 'BD_OwnerOrg';//货主类型
                    $Model[$k]['FOwnerId'] = $Purchaseorder['fpurchaseorgid_number'];;//货主编码
    
                    // $fbillno = DB::table('storagelocation')->select('owning_id','warehousecode','repositoryname')->where('id',$v['storagelocation'])->first();
                    // if(empty($fbillno)){
                    //      return throw new FailedException('库位出错');
                    // }
                    // if(isset($resdata[$fbillno->owning_id])){
                    //     $Model[$k]['FSTOCKID']= $resdata[$fbillno->owning_id]['FNumber'];
                    // }else{
                    //    return throw new FailedException('库位出错');
                    // }
                    $Storagelocation = Storagelocation::select(
                        'stash.fnumber',
                        'stash.fname',
                        'stash.fuseorgid_number',
                        'stash.fuseorgid_name',
                        'owning_id',
                        'storagelocation.warehousecode',
                        'storagelocation.repositoryname',
                        'storagelocation.id'
                    )
                    ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
                    ->where('storagelocation.id',$v['storagelocation'])
                    ->first();
                    if(empty($Storagelocation)){
                        return throw new FailedException('库位出错');
                    }
                    $Model[$k]['FSTOCKID']= $Storagelocation['fnumber'];//仓库名称
                    $Model[$k]['FGIVEAWAY'] = 'false';//赠品
            }
        }

        //旧系统的数据新系统退货
        if($returnnumber['incomingtype'] == 0 && $returnnumber['source'] == 1){
            //汇总查询 金蝶推送
            $data_source = PurchasereturnAttached::select(
                'fmaterialid',
                'fpurchaseorgid_number',
                'fpurchaseorgid_name',
                'fsupplierid_number',
                'fsupplierid_name',
                'fpersonnelunittime',
                'fownerid_number',
                'storagelocation',
                DB::raw('SUM(quantityreturned) as quantityreturned'),
                )
            ->where('purchasereturn_id',$id)
            ->groupby(['purchasereturn_id','fmaterialid','fpurchaseorgid_number','fpurchaseorgid_name','fsupplierid_number','fsupplierid_name','fpersonnelunittime','fownerid_number','storagelocation'])
            ->get()
            ->toArray();
            $fsupplierid_number = [];
            foreach($data_source as $k=>$v){
                $fsupplierid_number[] = $v['fsupplierid_number'];

                $Model[$k]['FMATERIALID'] = $v['fmaterialid']; //SKU（传编码）
                $Model[$k]['FUNITID'] = $v['funitid_number'];//单位（传编码）
                $Model[$k]['FQTY'] = $v['quantityreturned'];
                $Model[$k]['FOwnerTypeId'] = 'BD_OwnerOrg';//货主类型
                $Model[$k]['FOwnerId'] = $v['fpurchaseorgid_number'];;//货主编码
                $Model[$k]['FPERSONNELUNITTIME'] = $v['fpersonnelunittime'];
                $Model[$k]['FHRWORKTIME'] = $v['fpersonnelunittime']*$v['quantityreturned'];
                
            }

        }
    
       
        try {
            //开始起事务
            DB::beginTransaction();

        //   //组织间
        // if($returnnumber['incomingtype'] == 1){

        //             $PurchasereturnAttached = PurchasereturnAttached::select(
        //                 'purchasereturn_id',
        //                 'barcode',
        //                 'storagelocation',
        //                 'quantityreturned',
        //                 'purchasewarehousing_id',
        //                 'purchasewarehousing_materiel_id',//组织间物料表id
        //                 )
        //             ->where('purchasereturn_id',$id)
        //             ->get()
        //             ->toArray();

        //             //组织间退货 -》 生成退货表数据
        //             $Salesout_fbillno = Salesout::select('id','fbillno')->where('fbillno',$returnnumber['fbillno'])->first();
        //             if(empty($Salesout_fbillno)){
        //               return  throw new FailedException('亲，审核失败，无法获取销售单号');
        //             }
        //             $Purchasewdata = [];
        //             $Purchasewdata['returnnumber'] = 'ZZCGTH'.date('Ymd',time()).makeSerial();
        //             $Purchasewdata['incomingtype'] = 1;
        //             $Purchasewdata['fbillno'] = $Salesout_fbillno['fbillno'];
        //             $Purchasewdata['created_at'] = time();
        //             $Purchasewdata['updated_at'] = time();
        //             $Salesreturn_id = Salesreturn::insertGetId($Purchasewdata);
                      
        //             $salesreturn_attached = [];
        //             foreach($PurchasereturnAttached as $k=>$v){

        //                 $PurchasewarehousingMateriel = PurchasewarehousingMateriel::select(
        //                     'purchasewarehousing.warehosnumber',
        //                     'purchasewarehousing.fbillno',
        //                     'purchasewarehousing.fpurchaseorgid_number',
        //                     'purchasewarehousing.fpurchaseorgid_name',
        //                     'purchasewarehousing.fsupplierid_number',
        //                     'purchasewarehousing.fsupplierid_name',
        //                     'purchasewarehousing.fprovidercontactid',
        //                     'purchasewarehousing.fproviderphone',
        //                     'purchasewarehousing_materiel.fid',
        //                     'purchasewarehousing_materiel.fseq',
        //                     'purchasewarehousing_materiel.fentryid',
        //                     'purchasewarehousing_materiel.fmaterialid',
        //                     'purchasewarehousing_materiel.fmaterialname',
        //                     'purchasewarehousing_materiel.fmaterialmodel',
        //                     'purchasewarehousing_materiel.fmodel',
        //                     'purchasewarehousing_materiel.funitid_number',
        //                     'purchasewarehousing_materiel.funitid_name',
        //                     'purchasewarehousing_materiel.fstockid_number',
        //                     'purchasewarehousing_materiel.fstockid_name',
        //                     'purchasewarehousing_materiel.fmemo',
        //                     'purchasewarehousing_materiel.fownertypeid',
        //                     'purchasewarehousing_materiel.fownerid_number',
        //                     'purchasewarehousing_materiel.fownerid_name',
        //                     )
        //                 ->join('purchasewarehousing as purchasewarehousing', 'purchasewarehousing.id', '=', 'purchasewarehousing_materiel.purchasewarehousing_id')
        //                 ->where('purchasewarehousing_materiel.purchasereturn_id',$v['purchasewarehousing_materiel_id'])
        //                 ->where('purchasewarehousing.fbillno',$returnnumber['fbillno'])
        //                 ->where('purchasewarehousing.incomingtype',1)
        //                 ->first();
        //                 $Storagelocation = Storagelocation::select(
        //                     'stash.fnumber',
        //                     'stash.fname',
        //                     'stash.fuseorgid_number',
        //                     'stash.fuseorgid_name',
        //                     'owning_id',
        //                     'storagelocation.warehousecode',
        //                     'storagelocation.repositoryname',
        //                     'storagelocation.id'
        //                 )
        //                 ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
        //                 ->where('storagelocation.id',$v['storagelocation'])
        //                 ->first();
        //                 if(empty($Storagelocation)){
        //                     return throw new FailedException('库位出错');
        //                 }
        //                 //金蝶数据
        //                 $Model[$k]['FORGID'] = $PurchasewarehousingMateriel['fpurchaseorgid_number'];//组织编码
        //                 $Model[$k]['FSRCBILLNO'] = $returnnumber['fbillno'];//销售出原单号
        //                 $Model[$k]['FSRCSEQ'] = $PurchasewarehousingMateriel['fseq'];//原单行号
        //                 $Model[$k]['FMATERIALID'] = $PurchasewarehousingMateriel['fmaterialid'];    
        //                 $Model[$k]['FUNITID'] = $PurchasewarehousingMateriel['funitid_number'];
        //                 $Model[$k]['FQTY'] = $v['quantityreturned'];//退货数量
        //                 $Model[$k]['FOwnerTypeId'] = $PurchasewarehousingMateriel['fownertypeid'];//货主类型
        //                 $Model[$k]['FOwnerId'] = $PurchasewarehousingMateriel['fownerid_number'];//货主编码
        //                 $Model[$k]['FSRCID'] = $PurchasewarehousingMateriel['fid'];//行号id
        //                 $Model[$k]['FSRCENTRYID'] = $PurchasewarehousingMateriel['fentryid'];//单据合并
        //                 $Model[$k]['FSTOCKID']= $Storagelocation['fnumber'];//仓库名称
        //                 $Model[$k]['FGIVEAWAY'] = 'false';//赠品

        //                 // InventoryService::decInventory(
        //                 //     $PurchasewarehousingMateriel['fownerid_number'],
        //                 //     $returnnumber['returnnumber'],
        //                 //     $id,
        //                 //     InvTransDocType::PURCHASE_RECEIPT_RETURN_TISSUE->value,
        //                 //     $PurchasewarehousingMateriel['fmaterialid'],
        //                 //     $Storagelocation['warehousecode'],
        //                 //     $v['barcode'],
        //                 //     $v['quantityreturned'],
        //                 //     $PurchasewarehousingMateriel['fpurchaseorgid_number']
        //                 // );
        //                 // 组织间退货 -》生成销售退货表数据
        //                 // Salesreturn  SalesreturnAttached  SalesoutAttached  Salesout  SalesoutTiaoma
                        
        //                $dataresdata = SalesoutAttached::select('salesout_id','id','fmaterialid','fmaterialname','fmaterialmodel')
        //                 // ->join('salesout as salesout', 'salesout.id', '=', 'salesout_attached.salesout_id')
        //                 ->where('salesout_id',$Salesout_fbillno['id'])
        //                 ->where('fmaterialid',$PurchasewarehousingMateriel['fmaterialid'])
        //                 ->where('fmaterialname',$PurchasewarehousingMateriel['fmaterialname'])
        //                 ->where('fmaterialmodel',$PurchasewarehousingMateriel['fmaterialmodel'])
        //                 ->first();
                        
        //                 if(empty($dataresdata)){
        //                     return  throw new FailedException('亲，审核失败，无法获取销售单号物料信息哦');
        //                 }
        //                 $salesreturn_attached[$k]['salesreturn_id'] =  $Salesreturn_id;
        //                 $salesreturn_attached[$k]['salesout_id'] =  $dataresdata['salesout_id'];
        //                 $salesreturn_attached[$k]['salesout_attached_id'] =  $dataresdata['id'];
        //             }
                    
        //             $SalesreturnAttached_data = SalesreturnAttached::insert($purchasewarehousing_materiel);

        //             if(empty($SalesreturnAttached_data)){ return  throw new FailedException('亲，审核失败，无法生成销售退货单');}
        //     }else{
        //              //更新库存
        //             foreach($datares as $k=>$v){
        //                 $purdata = Purchaseorderschedule::query()->select('fseq','fmaterialid','funitid_number','purchaseorder_id','fownertypeid','fownerid_number','fownerid_name')
        //                 ->where('id',$v['purchaseorderschedule_id'])
        //                 ->groupby(['purchaseorder_id','fid','fseq','fmaterialid','fmaterialname','fmaterialmodel','fmodel','funitid_number'])
        //                 ->first();
        //                 $fbillno = DB::table('storagelocation')->select('owning_id','warehousecode','repositoryname')->where('id',$v['storagelocation'])->first();
        //                 $Purchaseorderdata = Purchaseorder::select('fbillno','fpurchaseorgid_number','fpurchaseorgid_name','fsupplierid_number','fpurchaseorgid_number')->where('id',$v['purchaseorder_id'])->first();//采购订单
                       
        //                     // InventoryService::decInventory(
        //                     //         $purdata['fownerid_number'],
        //                     //         $returnnumber['returnnumber'],
        //                     //         $id,
        //                     //         InvTransDocType::PURCHASE_RECEIPT_RETURN->value,
        //                     //         $purdata['fmaterialid'],
        //                     //         $fbillno->warehousecode,
        //                     //         $v['barcode'],
        //                     //         $v['quantityreturned'],
        //                     //         $Purchaseorderdata['fpurchaseorgid_number']
        //                     // );
        //             }
        //     }
        //更新状态
        Purchasereturn::query()->updateOrCreate(['id' => $id], [
            'state' => 1,
            'writestate' => 1,
        ]);  

        
        if($returnnumber['incomingtype'] == 0 && $returnnumber['source'] == 0){

            $datares = PurchasereturnAttached::select(
                'purchasereturn_id',
                'purchaseorder_id',
                'purchaseorderschedule_id',
                'barcode',
                'storagelocation',
                'quantityreturned'
                )
            ->where('purchasereturn_id',$id)
            ->get()
            ->toArray();
            if(empty($data)) throw new FailedException('退货数据出错');
                //更新库存
            foreach($datares as $k=>$v){
                $purdata = Purchaseorderschedule::query()->select('fseq','fmaterialid','funitid_number','purchaseorder_id','fownertypeid','fownerid_number','fownerid_name')
                ->where('id',$v['purchaseorderschedule_id'])
                ->groupby(['purchaseorder_id','fid','fseq','fmaterialid','fmaterialname','fmaterialmodel','fmodel','funitid_number'])
                ->first();
                $fbillno = DB::table('storagelocation')->select('owning_id','warehousecode','repositoryname')->where('id',$v['storagelocation'])->first();
                $Purchaseorderdata = Purchaseorder::select('fbillno','fpurchaseorgid_number','fpurchaseorgid_name','fsupplierid_number','fpurchaseorgid_number')->where('id',$v['purchaseorder_id'])->first();//采购订单
                    InventoryService::decInventory(
                            $purdata['fownerid_number'],
                            $returnnumber['returnnumber'],
                            $id,
                            InvTransDocType::PURCHASE_RECEIPT_RETURN->value,
                            $purdata['fmaterialid'],
                            $fbillno->warehousecode,
                            $v['barcode'],
                            $v['quantityreturned'],
                            $Purchaseorderdata['fpurchaseorgid_number']
                    );
            }
            $FEntity = [];
            foreach($Model as $k=>$v){
                $FEntity[$v['FORGID']][$k]['FSRCSEQ'] = $v['FSRCSEQ'];
                $FEntity[$v['FORGID']][$k]['FMATERIALID'] = $v['FMATERIALID'];
                $FEntity[$v['FORGID']][$k]['FUNITID'] = $v['FUNITID'];
                $FEntity[$v['FORGID']][$k]['FQTY'] = $v['FQTY'];
                $FEntity[$v['FORGID']][$k]['FSTOCKID'] = $v['FSTOCKID'];
                $FEntity[$v['FORGID']][$k]['FGIVEAWAY'] = $v['FGIVEAWAY'];
                $FEntity[$v['FORGID']][$k]['FSRCBILLNO'] = $v['FSRCBILLNO'];
                $FEntity[$v['FORGID']][$k]['FOwnerTypeId'] = $v['FOwnerTypeId'];
                $FEntity[$v['FORGID']][$k]['FOwnerId'] = $v['FOwnerId'];
            }


            foreach($FEntity as $k=>$v){
                $order = [
                    'FID'=>0,
                    'FORGID'=>$k,//组织（传编码）
                    'FBillNo'=>$returnnumber['returnnumber'],
                    'FDATE'=>date('Y-m-d H:i:s',time()),
                    'FBILLTYPEID'=>"PUR_MRB",
                    //'FSRCBILLNO'=>$k,
                    'FEntity'=>$v,
                ];
                //金蝶推送
                 (new KingDeeService())->form('TVJB_DJWMSDJ')->invokeSave($order);
            }
        }

        //旧系统的数据新系统退货
        if($returnnumber['incomingtype'] == 0 && $returnnumber['source'] == 1){

            $data_purchasereturn = PurchasereturnAttached::select(
                'fmaterialid',
                'purchasereturn_id',
                'fpurchaseorgid_number',
                'fpurchaseorgid_name',
                'fsupplierid_number',
                'fsupplierid_name',
                'fpersonnelunittime',
                'fownerid_number',
                'funitid_number',
                'barcode',
                'storagelocation',
                'quantityreturned',
                'source_number',
                )
            ->where('purchasereturn_id',$id)
            ->get()
            ->toArray();
            foreach($data_purchasereturn as $k=>$v){
                $fbillno = DB::table('storagelocation')->select('owning_id','warehousecode','repositoryname')->where('id',$v['storagelocation'])->first();
                $Purchaseorderdata = Purchaseorder::select('fbillno','fpurchaseorgid_number','fpurchaseorgid_name','fsupplierid_number','fpurchaseorgid_number')->where('id',$v['purchaseorder_id'])->first();//采购订单
                    InventoryService::decInventory(
                            $v['fownerid_number'],
                            $returnnumber['returnnumber'],
                            $id,
                            InvTransDocType::PURCHASE_RECEIPT_RETURN->value,
                            $v['fmaterialid'],
                            $fbillno->warehousecode,
                            $v['barcode'],
                            $v['quantityreturned'],
                            $v['fpurchaseorgid_number']
                    );
            }
            
            $FEntity = [];
            foreach($Model as $k=>$v){
                $FEntity[$v['FORGID']][$k]['FMATERIALID'] = $v['FMATERIALID'];
                $FEntity[$v['FORGID']][$k]['FUNITID'] = $v['FUNITID'];
                $FEntity[$v['FORGID']][$k]['FQTY'] = $v['FQTY'];
                $FEntity[$v['FORGID']][$k]['FOwnerTypeId'] = $v['FOwnerTypeId'];
                $FEntity[$v['FORGID']][$k]['FOwnerId'] = $v['FOwnerId'];
                $FEntity[$v['FORGID']][$k]['FPERSONNELUNITTIME'] = $v['FPERSONNELUNITTIME'];
                $FEntity[$v['FORGID']][$k]['FHRWORKTIME'] = $v['FHRWORKTIME'];
            }

            foreach($fsupplierid_number as $ks=>$vs){
                foreach($FEntity as $k=>$v){
                    $order = [
                        'FID'=>0,
                        'FORGID'=>$k,//组织（传编码）
                        'FMRREASON'=>$vs,
                        'FBillNo'=>$returnnumber['returnnumber'],
                        'FDATE'=>date('Y-m-d H:i:s',time()),
                        'FBILLTYPEID'=>"PUR_MRB",
                        //'FSRCBILLNO'=>$k,
                        'FEntity'=>$v,
                    ];
                    //金蝶推送
                     (new KingDeeService())->form('TVJB_DJWMSDJ')->invokeSave($order);
                }
            }


        }
            
            DB::commit();
            return ['code'=>1000,'message'=>'审核成功'];

        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }

    }
    


  
    /* 采购退货PDA 扫描接口
     * @param $id
     * @return void
     */
    public static function checkPdaApi($code)
    {
               

                $data = Inventory::select('id','qty','org_code','location','material_no','unit','lot_num','assign_qty','lock_qty','supplier_code','wms_code')
                ->where('lot_num',$code)
                ->get()
                ->toArray();
               
                if(empty($data)){
                    return throw new FailedException('亲！库存没有该箱号。');
                }
                $source = 1;
            foreach($data as $k=>$v){
                   
                $Purchaseorder_id = Purchaseorder::select('id','fbillno','fid','fsupplierid_number','fsupplierid_name','fpurchaseorgid_number','fpurchaseorgid_name')->where('fbillno',$v['supplier_code'])->first();
                    //判断库存来源单号是否是采购订单号
                     $data[$k]['fmasterid'] = '';
                     $data[$k]['purchasewarehousing_id'] = '';
                if(!empty($Purchaseorder_id)){
                    
                        $source = 0;
                        $Purchaseorderschedule = Purchaseorderschedule::select(
                            'fmaterialid',
                            'fmaterialname',
                            'fmaterialmodel',
                            'fmodel',
                            'funitid_name',
                            'funitid_number',
                            'fqty',
                            'purchaseorder_id',
                            'id',
                            'fmasterid',
                            )
                            ->where('purchaseorder_id',$Purchaseorder_id['id'])
                            ->where('fmaterialid',$v['material_no'])
                            ->where('funitid_number',$v['unit'])
                            ->first();
                            if(empty($Purchaseorderschedule)){
                                return throw new FailedException('亲！扫描出错采购采购订单找不到这个物料信息，请联系技术处理。');
                            }
                       
                            
                            $Provisionalschedule = Provisionalschedule::select(
                                'provisional.ordernumber',
                                'provisionalschedule.id',
                                'provisionalschedule.putquantity',
                                'provisionalschedule.giveaway',
                                'provisionalschedule.provisional_id',
                                'provisionalschedule.purchaseorder_id',
                                'provisionalschedule.supplier_id',
                                'provisionalschedule.supplierschedule_id',
                                'provisionalschedule.quantityreceived',
                                'provisionalschedule.barcode',
                                'provisionalschedule.storagelocation',
                                'provisionalschedule.inspectionlist_id',
                                'provisionalschedule.purchasewarehousing_id',
                                'provisionalschedule.purchaseorderschedule_id',
                                )
                                ->join('provisional as provisional', 'provisional.id', '=', 'provisionalschedule.provisional_id')
                                ->where('provisionalschedule.barcode',$code)
                                ->where('provisionalschedule.purchaseorder_id',$Purchaseorder_id['id'])
                                ->where('provisionalschedule.purchaseorderschedule_id',$Purchaseorderschedule['id'])
                                ->first();
                               
                                $data[$k]['provisionalschedule_id'] = $Provisionalschedule['id'];//暂收单id
                                $data[$k]['purchaseorderschedule_id'] = $Provisionalschedule['purchaseorderschedule_id'];
                                
                                
                                $Supplierschedule = supplier::select('supplierOrder')->where('id',$Provisionalschedule['supplier_id'])
                                ->first();
                        
                                $data[$k]['supplierOrder'] = $Supplierschedule['supplierOrder'];//供应商单号

                                $data[$k]['fbillno'] = $Purchaseorder_id['fbillno'];
                                $data[$k]['fsupplierid_number'] = $Purchaseorder_id['fsupplierid_number'];
                                $data[$k]['fsupplierid_name'] = $Purchaseorder_id['fsupplierid_name'];
                                $data[$k]['fmaterialid'] = $Purchaseorderschedule['fmaterialid'];
                                $data[$k]['fmaterialname'] = $Purchaseorderschedule['fmaterialname'];
                                $data[$k]['fmaterialmodel'] = $Purchaseorderschedule['fmaterialmodel'];
                                $data[$k]['fmodel'] = $Purchaseorderschedule['fmodel'];
                                $data[$k]['funitid_name'] = $Purchaseorderschedule['funitid_name'];
                                $data[$k]['fmasterid'] = $Purchaseorderschedule['fmasterid'];
                                // $data['fid'] = $Purchaseorderschedule['fid'];
                                // $data['fseq'] = $Purchaseorderschedule['fseq'];
                                // $data['fqty'] = $purid['fqty'];//采购订单数量
                                $data[$k]['purchaseorder_id'] = $Purchaseorder_id['id'];
                                
                               
                                $purchasewarehousing = Purchasewarehousing::select('warehosnumber','id')->where('id',$Provisionalschedule['purchasewarehousing_id'])->first();
                                 
                                if(!empty($purchasewarehousing)){
                                    $data[$k]['warehosnumber'] = $purchasewarehousing['warehosnumber'];
                                    $data[$k]['purchasewarehousing_id'] = $purchasewarehousing['id'];
                                }
                                
                                

                                // $data[$k]['fpurchaseorgid_number'] = $purchasewarehousing['fpurchaseorgid_number'];
                                // $data[$k]['fpurchaseorgid_name'] = $purchasewarehousing['fpurchaseorgid_name'];
                                $data[$k]['fownerid_number'] = $v['org_code'];
                                $data[$k]['purchasewarehousing_id'] = $Provisionalschedule['purchasewarehousing_id'];

                }
                    $Storagelocation = Storagelocation::select(
                    'stash.fnumber',
                    'stash.fname',
                    'stash.fuseorgid_number',
                    'stash.fuseorgid_name',
                    'owning_id',
                    'storagelocation.warehousecode',
                    'storagelocation.repositoryname',
                    'storagelocation.id'
                    )
                    ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
                    ->where('stash.fnumber',$v['wms_code'])
                    ->where('storagelocation.warehousecode',$v['location'])
                    ->first();
                    $data[$k]['fpurchaseorgid_name'] = $Storagelocation['fuseorgid_name'];
                    $data[$k]['fpurchaseorgid_number'] = $Storagelocation['fuseorgid_number'];
 
                    $Material = Material::select('id')->where('fnumber',$v['material_no'])->first();
                    
                    if(!empty($Material)){
                        $data[$k]['fmasterid'] = $Material['id'];
                    }
                    
                    $data[$k]['fname'] = $Storagelocation['fname'];
                    $data[$k]['fnumber'] = $Storagelocation['fnumber'];
                    $data[$k]['warehousecode'] = $Storagelocation['warehousecode'];
                    $data[$k]['repositoryname'] = $Storagelocation['repositoryname'];
                    $data[$k]['quantityreturned'] = '';//退货数量
                    //库存数量
                    $data[$k]['inventory_qty'] = $v['qty'] - $v['assign_qty'] - $v['lock_qty'];
                    $data[$k]['storagelocation_id'] = $Storagelocation['id'];
                    $data[$k]['fpersonnelunittime'] = '';//单价
                    $data[$k]['funitid_number'] = $v['unit'];
                    $data[$k]['fmaterialid'] = $v['material_no'];
                    $data[$k]['source'] = $source;
                    $data[$k]['source_number'] = $v['supplier_code'];
                    
                    

            }

            return ['code'=>1000,'message'=>'扫描成功','data'=>$data];
        

    }

    /**
     * @param $id
     * @return void
     */
    public static function showdata($purchasereturn,$data)
    {
       
        $res = [];
        $kingDeeService = new warehouseService();
        $resdata = $kingDeeService->warehousedataApiTwo();
        $datauser = $kingDeeService->uerdata();
         
        //组织间
        if($purchasereturn['incomingtype'] == 1){
            $data = PurchasereturnAttached::select('purchasereturn_id','barcode','storagelocation','purchasewarehousing_id','purchasewarehousing_materiel_id')
                ->where('purchasereturn_id',$purchasereturn['id'])
                ->get()
                ->toArray();
              
                foreach($data as $k=>$v){
                
                    $datares_data = PurchasewarehousingMateriel::select(
                        'purchasewarehousing.warehosnumber',
                        'purchasewarehousing.fbillno',
                        'purchasewarehousing.fpurchaseorgid_number',
                        'purchasewarehousing.fpurchaseorgid_name',
                        'purchasewarehousing.fsupplierid_number',
                        'purchasewarehousing.fsupplierid_name',
                        'purchasewarehousing.fprovidercontactid',
                        'purchasewarehousing.fproviderphone',
                        'purchasewarehousing_materiel.fid',
                        'purchasewarehousing_materiel.fseq',
                        'purchasewarehousing_materiel.fentryid',
                        'purchasewarehousing_materiel.fmaterialid',
                        'purchasewarehousing_materiel.fmaterialname',
                        'purchasewarehousing_materiel.fmaterialmodel',
                        'purchasewarehousing_materiel.fmodel',
                        'purchasewarehousing_materiel.funitid_number',
                        'purchasewarehousing_materiel.funitid_name',
                        'purchasewarehousing_materiel.fstockid_number',
                        'purchasewarehousing_materiel.fstockid_name',
                        'purchasewarehousing_materiel.fmemo',
                        'purchasewarehousing_materiel.fownertypeid',
                        'purchasewarehousing_materiel.fownerid_number',
                        'purchasewarehousing_materiel.fownerid_name',)
                     ->join('purchasewarehousing as purchasewarehousing', 'purchasewarehousing.id', '=', 'purchasewarehousing_materiel.purchasewarehousing_id')
                    ->where('purchasewarehousing_materiel.id',$v['purchasewarehousing_materiel_id'])
                    ->first();
                   
                    
                    //  $datares_data = PurchasewarehousingMateriel::select('*')
                    // ->where('id',$v['purchasewarehousing_materiel_id'])
                    // ->first();
    
                    $fbillno = DB::table('storagelocation')->select('owning_id','warehousecode','repositoryname')->find($v['storagelocation']);
                    if(isset($resdata[$fbillno->owning_id])){
                        $data[$k]['FName'] = $resdata[$fbillno->owning_id]['FName'];
                        $data[$k]['FNumber'] = $resdata[$fbillno->owning_id]['FNumber'];
                    }
                    
                    $data[$k]['warehousecode'] =$fbillno->warehousecode;
                    $data[$k]['repositoryname'] = $fbillno->repositoryname;
                    $data[$k]['fbillno'] = $datares_data['fbillno'];
                    $data[$k]['fsupplierid_number'] = $datares_data['fsupplierid_number'];
                    $data[$k]['fsupplierid_name'] = $datares_data['fsupplierid_name'];
                    $data[$k]['fid'] = $datares_data['fid'];
                    $data[$k]['fseq'] = $datares_data['fseq'];
                    $data[$k]['fentryid'] = $datares_data['fentryid'];
                    $data[$k]['fmaterialid'] = $datares_data['fmaterialid'];
                    $data[$k]['fmaterialname'] = $datares_data['fmaterialname'];
                    $data[$k]['fmaterialmodel'] = $datares_data['fmaterialmodel'];
                    $data[$k]['fmodel'] = $datares_data['fmodel'];
                    $data[$k]['funitid_number'] = $datares_data['funitid_number'];
                    $data[$k]['funitid_name'] = $datares_data['funitid_name'];
                    $data[$k]['fstockid_number'] = $datares_data['fstockid_number'];
                    $data[$k]['fstockid_name'] = $datares_data['fstockid_name'];
                    $data[$k]['fmemo'] = $datares_data['fmemo'];
                    $data[$k]['fownertypeid'] = $datares_data['fownertypeid'];
                    $data[$k]['fownerid_number'] = $datares_data['fownerid_number'];
                    $data[$k]['quantityreturned'] = $datares_data['quantityreturned'];
                    
                    
                }

        }else{
            //采购来源退料查询
            if($purchasereturn['source'] == 0){

                if(isset($data['detailsAll'])){
           
                    $data = PurchasereturnAttached::select(
                        'purchasereturn_id',
                        'purchaseorder_id',
                        'purchaseorderschedule_id',
                        // 'barcode',
                        'storagelocation',
                        DB::raw('SUM(quantityreturned) as quantityreturned'),
                        )
                    ->where('purchasereturn_id',$purchasereturn['id'])
                    ->groupby(['purchasereturn_id','purchaseorder_id','purchaseorderschedule_id','storagelocation'])
                    ->get()
                    ->toArray();
                  
                }else{
                   
                    $data = PurchasereturnAttached::
                    where('purchasereturn_id',$purchasereturn['id'])
                    ->get()->toArray();
                    
                } 
                
                foreach($data as $k=>$v){  
                    // $supplierOrder = Supplier::select('supplierOrder')->where('id',$vs['supplier_id'])->first();
                    // $datares[$k]['supplierOrder'] = $supplierOrder['supplierOrder'];//送货单号
                    
                    
                    $fbillno = DB::table('storagelocation')->select('owning_id','warehousecode','repositoryname')->find($v['storagelocation']);
                    if(isset($resdata[$fbillno->owning_id])){
                        $data[$k]['FName'] = $resdata[$fbillno->owning_id]['FName'];
                        $data[$k]['FNumber'] = $resdata[$fbillno->owning_id]['FNumber'];
                    }
                    
                    $data[$k]['warehousecode'] =$fbillno->warehousecode;
                    $data[$k]['repositoryname'] = $fbillno->repositoryname;
                     
                    // $Supplierschedule = Supplierschedule::select('purchaseorderschedule_id')
                    // ->whereIn('id',$v['supplierschedule_id'])->groupby(['purchaseorderschedule_id'])
                    // ->get()->toArray();
                    
                    // $purchaseorderschedule_id = [];
                    // foreach($Supplierschedule as $kk=>$vv){
                    //     $purchaseorderschedule_id[] = $vv['purchaseorderschedule_id'];
                    // }    
          
                    //合并后的物料数量
                    $Purchaseorderschedule = Purchaseorderschedule::select('purchaseorder_id','fseq','fmaterialid','fmaterialname','fmaterialmodel','funitid_name')
                    ->where('id',$v['purchaseorderschedule_id'])->first();
     
                    // $Purchaseorderschedule = Purchaseorderschedule::select('fmaterialid','fmaterialname','fmaterialmodel','funitid_name')
                    // ->where('fseq',$SUMfqty['fseq'])->first()->toArray();
                    $data[$k]['fseq'] = $Purchaseorderschedule['fseq'];
                    $data[$k]['fmaterialid'] = $Purchaseorderschedule['fmaterialid'];
                    $data[$k]['fmaterialname'] = $Purchaseorderschedule['fmaterialname'];
                    $data[$k]['fmaterialmodel'] = $Purchaseorderschedule['fmaterialmodel'];
                    $data[$k]['funitid_name'] = $Purchaseorderschedule['funitid_name'];
                    // $data[$k]['fqty'] = $Purchaseorderschedule['fqty'];
        
                    $fbillno = Purchaseorder::select('fbillno','fsupplierid_number','fsupplierid_name')->where('id',$Purchaseorderschedule['purchaseorder_id'])->first()->toArray();
                    $data[$k]['fbillno'] = $fbillno['fbillno'];//采购订单号
                    $data[$k]['fsupplierid_number'] = $fbillno['fsupplierid_number'];
                    $data[$k]['fsupplierid_name'] = $fbillno['fsupplierid_name'];
                    
                }


            }else{

                 
                if(isset($data['detailsAll'])){
           
                    $data = PurchasereturnAttached::select(
                        'purchasereturn_id',
                        'fmaterialid',
                        'fpurchaseorgid_number',
                        'fsupplierid_number',
                        'fsupplierid_name',
                        'fownerid_number',
                        'storagelocation',
                        DB::raw('SUM(quantityreturned) as quantityreturned'),
                        )
                    ->where('purchasereturn_id',$purchasereturn['id'])
                    ->groupby(['purchasereturn_id','fmaterialid','fpurchaseorgid_number','storagelocation','fsupplierid_number','fsupplierid_name','fownerid_number'])
                    ->get()
                    ->toArray();
                   
                  
                }else{
              
                    
                    $data = PurchasereturnAttached::
                    where('purchasereturn_id',$purchasereturn['id'])
                    ->get()
                    ->toArray();
      
                } 

                foreach($data as $k=>$v){  
                  
                    $fbillno = DB::table('storagelocation')->select('owning_id','warehousecode','repositoryname')->find($v['storagelocation']);
                    if(isset($resdata[$fbillno->owning_id])){
                        $data[$k]['FName'] = $resdata[$fbillno->owning_id]['FName'];
                        $data[$k]['FNumber'] = $resdata[$fbillno->owning_id]['FNumber'];
                    }
                    $data[$k]['warehousecode'] =$fbillno->warehousecode;
                    $data[$k]['repositoryname'] = $fbillno->repositoryname;
                    $data[$k]['fseq'] = '';
                    $data[$k]['fmaterialname'] = '';
                    $data[$k]['fmaterialmodel'] = '';
                    $data[$k]['funitid_name'] = '';
                    $data[$k]['fsupplierid_number'] = $fbillno['fsupplierid_number'];
                    $data[$k]['fsupplierid_name'] = $fbillno['fsupplierid_name'];                   
                }

            }

            



        }

        return $data;
    }

    /*
    *组织间退货 采购退货货单PDA扫描接口
    * @param $id
    * @return mixed
    */
    public static function intertissueturnData($code)
    {

       $datares = [];
        $SalesoutTiaoma = SalesoutTiaoma::where('barcode',$code)->first();
        if(empty($SalesoutTiaoma)){
                return throw new FailedException('亲！该组织间没有这个箱号。');
        }
     
        $SalesoutAttached = SalesoutAttached::select(
            'salesout.fbillno',
            'salesout.fsaleorgid_number',
            'salesout.fsaleorgid_name',
            'salesout.fcustomerid_number',
            'salesout.fcustomerid_name',
            'salesout.fpurchaseorgid_number',
            'salesout.fpurchaseorgid_name',
            'salesout.fsupplierid_number',
            'salesout.fsupplierid_name',
            'salesout.incomingtype',
            'salesout_attached.fentryid',
            'salesout_attached.fmaterialid',
            'salesout_attached.fmaterialname',
            'salesout_attached.fmaterialmodel',
            'salesout_attached.funitid_name',
            'salesout_attached.fid',
            'salesout_attached.fseq',
            'salesout_attached.fentryid',
            )
        ->join('salesout as salesout', 'salesout.id', '=', 'salesout_attached.salesout_id')
        ->where('salesout_attached.salesout_id',$SalesoutTiaoma['salesout_id'])
        ->where('salesout_attached.id',$SalesoutTiaoma['salesout_attached_id'])
        ->where('salesout.incomingtype',1)
        ->first();
        if(empty($SalesoutAttached)){
            return throw new FailedException('亲！销售出单没有该箱号。');
        }
        
        $dataresdata = PurchasewarehousingMateriel::select(
                    'purchasewarehousing.fpurchaseorgid_number',
                    'purchasewarehousing.fbillno',
                    'purchasewarehousing.id as purchasewarehousing_id',
                    'purchasewarehousing.warehosnumber',
                    'purchasewarehousing.fpurchaseorgid_name',
                    'purchasewarehousing.fsupplierid_number',
                    'purchasewarehousing.fsupplierid_name',
                    'purchasewarehousing_materiel.fmaterialid',
                    'purchasewarehousing_materiel.fmaterialname',
                    'purchasewarehousing_materiel.fmaterialmodel',
                    'purchasewarehousing_materiel.fmodel',
                    'purchasewarehousing_materiel.funitid_number',
                    'purchasewarehousing_materiel.funitid_name',
                    'purchasewarehousing_materiel.fstockid_number',
                    'purchasewarehousing_materiel.fstockid_name',
                    'purchasewarehousing_materiel.putquantity',
                    'purchasewarehousing_materiel.id as purchasewarehousing_materiel_id',
                    'purchasewarehousing_materiel.fownerid_number',
                    'purchasewarehousing.incomingtype',
                    )
                ->join('purchasewarehousing as purchasewarehousing', 'purchasewarehousing.id', '=', 'purchasewarehousing_materiel.purchasewarehousing_id')
                ->where('purchasewarehousing.id',$SalesoutTiaoma['purchasewarehousing_id'])
                ->where('purchasewarehousing_materiel.id',$SalesoutTiaoma['purchasewarehousing_materiel'])
                ->where('purchasewarehousing_materiel.fmaterialid',$SalesoutAttached['fmaterialid'])//sku
                ->where('purchasewarehousing_materiel.fid',$SalesoutAttached['fid'])//fid
                ->where('purchasewarehousing_materiel.fseq',$SalesoutAttached['fseq'])//fseq
                ->where('purchasewarehousing_materiel.fentryid',$SalesoutAttached['fentryid'])//fentryid
                ->where('purchasewarehousing.incomingtype',1)
                // ->where('purchasewarehousing_materiel.barcode',$v['lot_num'])//箱号
                // ->where('storagelocation',$Storagelocation['id'])//库位ID
                ->first();
        if(empty($dataresdata)){
            return throw new FailedException('亲！组织间入库单没有该箱号。');
        }
        
     $Storagelocation = Storagelocation::select(
            'stash.fnumber',
            'stash.fname',
            'stash.fuseorgid_number',
            'stash.fuseorgid_name',
            'owning_id',
            'storagelocation.warehousecode',
            'storagelocation.repositoryname',
            'storagelocation.id'
            )
        ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
        ->where('storagelocation.id',$SalesoutTiaoma['storagelocation_put'])
        // ->where('stash.fnumber',$v['wms_code'])
        ->first();
        
        if(empty($Storagelocation)){
            return throw new FailedException('亲！库位出错。');
        }
        
        $inventory = Inventory::select('org_code','location','material_no','unit','lot_num','qty','cargo_code','wms_code','cargo_code','assign_qty','lock_qty')
        ->where('lot_num',$code)
        ->where('wms_code',$Storagelocation['fnumber'])
        ->where('location',$Storagelocation['warehousecode'])
        ->where('material_no',$dataresdata['fmaterialid'])
        ->where('org_code',$dataresdata['fpurchaseorgid_number'])//组织代码
        ->where('cargo_code',$dataresdata['fownerid_number'])//货主
        ->first();
        // ->toArray();
        // p($inventory);
        // exit;
        // p($Storagelocation['fnumber']);
        // p($Storagelocation['warehousecode']);
        // p($dataresdata['fmaterialid']);
        // p($dataresdata['fpurchaseorgid_number']);
        // p($dataresdata['fownerid_number']);

        if(empty($inventory)){
            return ['code'=>10005,'message'=>'条码出错'];
        }
        $datares['storagelocation'] = $Storagelocation['id'];
        $datares['fnumber'] = $Storagelocation['fnumber'];
        $datares['fname'] = $Storagelocation['fname'];
        $datares['warehousecode'] = $Storagelocation['warehousecode'];
        $datares['repositoryname'] = $Storagelocation['repositoryname'];
        $datares['funitid_name'] = $dataresdata['fname'];
       
        $datares['funitid_number'] = $dataresdata['funitid_number'];
        $datares['fmodel'] = $dataresdata['fmodel'];
        $datares['fmaterialmodel'] = $dataresdata['fmaterialmodel'];
        $datares['fmaterialname'] = $dataresdata['fmaterialname'];
        $datares['fmaterialid'] = $dataresdata['fmaterialid'];
        $datares['warehosnumber'] = $dataresdata['warehosnumber'];
        $datares['fbillno'] = $dataresdata['fbillno'];
        $datares['purchasewarehousing_id'] = $dataresdata['purchasewarehousing_id'];
        $datares['purchasewarehousing_materiel_id'] = $dataresdata['purchasewarehousing_materiel_id'];
        $datares['barcode'] = $code;
        $datares['putquantity'] = $SalesoutTiaoma['putquantity'];

        $datares['qty'] = $inventory['qty'] - $inventory['assign_qty'] - $inventory['lock_qty'];    
        $datares['incomingtype'] = $dataresdata['incomingtype'];
        
        return ['code'=>1000,'message'=>'扫描成功','data'=>$datares];
    }

   
    /*
    *组织间退货 采购退货货单PDA扫描接口
    * @param $id
    * @return mixed
    */
    // public static function intertissueturnData($code)
    // {
    //     $inventory = Inventory::select('org_code','location','material_no','unit','lot_num','qty','cargo_code','wms_code')
    //     ->where('lot_num',$code)
    //     ->get()
    //     ->toArray();
        
    //     if(empty($inventory)){
    //         return ['code'=>10005,'message'=>'条码出错'];
    //     }
    //     $datares = [];
    //     $SalesoutTiaoma = SalesoutTiaoma::where('barcode',$code)->first();
    //     if(empty($SalesoutTiaoma)){
    //         return throw new FailedException('亲！该组织间没有这个箱号。');
    //     }

    //     foreach($inventory as $k=>$v){


    //         $Storagelocation = Storagelocation::select(
    //             'stash.fnumber',
    //             'stash.fname',
    //             'stash.fuseorgid_number',
    //             'stash.fuseorgid_name',
    //             'owning_id',
    //             'storagelocation.warehousecode',
    //             'storagelocation.repositoryname',
    //             'storagelocation.id'
    //             )
    //         ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
    //         ->where('storagelocation.warehousecode',$v['location'])
    //         ->where('stash.fnumber',$v['wms_code'])
    //         ->first();
          
    //         if(!empty($Storagelocation)){

    //             $dataresdata = PurchasewarehousingMateriel::select(
    //                 'purchasewarehousing.fpurchaseorgid_number',
    //                 'purchasewarehousing.fbillno',
    //                 'purchasewarehousing.id as purchasewarehousing_id',
    //                 'purchasewarehousing.warehosnumber',
    //                 'purchasewarehousing.fpurchaseorgid_name',
    //                 'purchasewarehousing.fsupplierid_number',
    //                 'purchasewarehousing.fsupplierid_name',
    //                 'purchasewarehousing_materiel.fmaterialid',
    //                 'purchasewarehousing_materiel.fmaterialname',
    //                 'purchasewarehousing_materiel.fmaterialmodel',
    //                 'purchasewarehousing_materiel.fmodel',
    //                 'purchasewarehousing_materiel.funitid_number',
    //                 'purchasewarehousing_materiel.funitid_name',
    //                 'purchasewarehousing_materiel.fstockid_number',
    //                 'purchasewarehousing_materiel.fstockid_name',
    //                 'purchasewarehousing_materiel.putquantity',
    //                 'purchasewarehousing_materiel.id as purchasewarehousing_materiel_id',
    //                 'purchasewarehousing_materiel.barcode',
    //                 )
    //             ->join('purchasewarehousing as purchasewarehousing', 'purchasewarehousing.id', '=', 'purchasewarehousing_materiel.purchasewarehousing_id')
    //             ->where('purchasewarehousing.fpurchaseorgid_number',$v['org_code'])//组织代码
    //             ->where('purchasewarehousing_materiel.fownerid_number',$v['cargo_code'])//货主
    //             ->where('purchasewarehousing_materiel.fmaterialid',$v['material_no'])//sku
    //             // ->where('purchasewarehousing_materiel.barcode',$v['lot_num'])//箱号
    //             // ->where('storagelocation',$Storagelocation['id'])//库位ID
    //             ->first();

    //             if(!empty($dataresdata)){
    //                 $datares[$k]['storagelocation'] = $Storagelocation['id'];
    //                 $datares[$k]['fnumber'] = $Storagelocation['fnumber'];
    //                 $datares[$k]['fname'] = $Storagelocation['fname'];
    //                 $datares[$k]['warehousecode'] = $Storagelocation['warehousecode'];
    //                 $datares[$k]['repositoryname'] = $Storagelocation['repositoryname'];
    //                 $datares[$k]['funitid_name'] = $dataresdata['fname'];
    //                 $datares[$k]['barcode'] = $dataresdata['barcode'];
    //                 $datares[$k]['funitid_number'] = $dataresdata['funitid_number'];
    //                 $datares[$k]['fmodel'] = $dataresdata['fmodel'];
    //                 $datares[$k]['fmaterialmodel'] = $dataresdata['fmaterialmodel'];
    //                 $datares[$k]['fmaterialname'] = $dataresdata['fmaterialname'];
    //                 $datares[$k]['fmaterialid'] = $dataresdata['fmaterialid'];
    //                 $datares[$k]['warehosnumber'] = $dataresdata['warehosnumber'];
    //                 $datares[$k]['fbillno'] = $dataresdata['fbillno'];
    //                 $datares[$k]['purchasewarehousing_id'] = $dataresdata['purchasewarehousing_id'];
    //                 $datares[$k]['purchasewarehousing_materiel_id'] = $dataresdata['purchasewarehousing_materiel_id'];
    //             }

    //         }
  
    //     }
    //     if(empty($datares)){
    //         return throw new FailedException('亲！该箱号不属于组织间的退货。');
    //     }
       
        
        
    //     return ['code'=>1000,'message'=>'扫描成功','data'=>$datares];
    // }

    
     /*
    数据添加方法
    */
    public static function returnDataAdd(array $data)
    {
        
        $Purchasereturn = new Purchasereturn;
        return self::returnDataAddTwo($Purchasereturn, $data);
    }

    //数据添加方法
    public static function returnDataAddTwo(Purchasereturn $Purchasereturn,$data)
    {

        
        try {
            //开始起事务
            DB::beginTransaction();
            
            //先生成退货单
            $Purchasewdata = [];
            // $Purchasewdata['returnnumber'] = 'ZHCGTH'.date('Ymd',time()).makeSerial();
            $Purchasewdata['returnnumber'] = \App\Services\UnitService::createDocno(\App\Enums\OrderNoPrefix::NO_CGTH->value);
            $Purchasewdata['incomingtype'] = 1;
            $Purchasewdata['fbillno'] = $data['fbillno'];
            $Purchasewdata['creator_id'] = $data['creator_id'];
            // $Purchasewdata['remarks'] = '';
            $Purchasereturn->fill($Purchasewdata);
            $Purchasereturn->save();
 
            foreach($data['detailscheck_all'] as $k=>$v){
                $data['detailscheck_all'][$k]['purchasereturn_id'] =  $Purchasereturn['id'];
                // $datares = [
                //     'purchasereturn_id' => $Purchasereturn['id'],
                //     'purchasewarehousing_materiel_id' => $v['purchasewarehousing_materiel_id'],//组织间入库附表
                //     'purchasewarehousing_id' => $v['purchasewarehousing_id'],//采购入库单id
                //     'storagelocation' => $v['storagelocation'],
                //     'quantityreturned' => $v['quantityreturned'],
                //     'barcode' => $v['barcode'],
                // ];
            }      

            PurchasereturnAttached::insert($data['detailscheck_all']);

            //金蝶推送
            $PurchasereturnAttached = PurchasereturnAttached::select(
                'purchasereturn_id',
                'barcode',
                'storagelocation',
                'quantityreturned',
                'purchasewarehousing_id',
                'purchasewarehousing_materiel_id',//组织间物料表id
                )
            ->where('purchasereturn_id',$Purchasereturn['id'])
            ->get()
            ->toArray();
            
           

   
            //组织间退货 -》 生成退货表数据
            $Salesout_fbillno = Salesout::select('id','fbillno')->where('fbillno',$data['fbillno'])->first();
           
            if(empty($Salesout_fbillno)){
              return  throw new FailedException('亲，审核失败，无法获取销售单号');
            }
            
            $Purchasewdata = [];
            // $Purchasewdata['returnnumber'] = 'ZZCGTH'.date('Ymd',time()).makeSerial();
            $Purchasewdata['returnnumber'] = \App\Services\UnitService::createDocno(\App\Enums\OrderNoPrefix::NO_ZZCGTH->value);
            $Purchasewdata['incomingtype'] = 1;
            $Purchasewdata['fbillno'] = $Salesout_fbillno['fbillno'];
            $Purchasewdata['created_at'] = time();
            $Purchasewdata['updated_at'] = time();
            $Salesreturn_id = Salesreturn::insertGetId($Purchasewdata);
              
            
            $salesreturn_attached = [];
            foreach($PurchasereturnAttached as $k=>$v){

                $PurchasewarehousingMateriel = PurchasewarehousingMateriel::select(
                    'purchasewarehousing.warehosnumber',
                    'purchasewarehousing.fbillno',
                    'purchasewarehousing.fpurchaseorgid_number',
                    'purchasewarehousing.fpurchaseorgid_name',
                    'purchasewarehousing.fsupplierid_number',
                    'purchasewarehousing.fsupplierid_name',
                    'purchasewarehousing.fprovidercontactid',
                    'purchasewarehousing.fproviderphone',
                    'purchasewarehousing_materiel.fid',
                    'purchasewarehousing_materiel.fseq',
                    'purchasewarehousing_materiel.fentryid',
                    'purchasewarehousing_materiel.fmaterialid',
                    'purchasewarehousing_materiel.fmaterialname',
                    'purchasewarehousing_materiel.fmaterialmodel',
                    'purchasewarehousing_materiel.fmodel',
                    'purchasewarehousing_materiel.funitid_number',
                    'purchasewarehousing_materiel.funitid_name',
                    'purchasewarehousing_materiel.fstockid_number',
                    'purchasewarehousing_materiel.fstockid_name',
                    'purchasewarehousing_materiel.fmemo',
                    'purchasewarehousing_materiel.fownertypeid',
                    'purchasewarehousing_materiel.fownerid_number',
                    'purchasewarehousing_materiel.fownerid_name',
                    )
                ->join('purchasewarehousing as purchasewarehousing', 'purchasewarehousing.id', '=', 'purchasewarehousing_materiel.purchasewarehousing_id')
                ->where('purchasewarehousing_materiel.id',$v['purchasewarehousing_materiel_id'])
                ->where('purchasewarehousing.fbillno',$data['fbillno'])
                ->where('purchasewarehousing.incomingtype',1)
                ->first();
                $Storagelocation = Storagelocation::select(
                    'stash.fnumber',
                    'stash.fname',
                    'stash.fuseorgid_number',
                    'stash.fuseorgid_name',
                    'owning_id',
                    'storagelocation.warehousecode',
                    'storagelocation.repositoryname',
                    'storagelocation.id'
                )
                ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
                ->where('storagelocation.id',$v['storagelocation'])
                ->first();
                if(empty($Storagelocation)){
                    return throw new FailedException('库位出错');
                }

                //金蝶数据
                $Model[$k]['FORGID'] = $PurchasewarehousingMateriel['fpurchaseorgid_number'];//组织编码
                $Model[$k]['FSRCBILLNO'] = $data['fbillno'];//销售出原单号
                $Model[$k]['FSRCSEQ'] = $PurchasewarehousingMateriel['fseq'];//原单行号
                $Model[$k]['FMATERIALID'] = $PurchasewarehousingMateriel['fmaterialid'];    
                $Model[$k]['FUNITID'] = $PurchasewarehousingMateriel['funitid_number'];
                $Model[$k]['FQTY'] = $v['quantityreturned'];//退货数量
                $Model[$k]['FOwnerTypeId'] = $PurchasewarehousingMateriel['fownertypeid'];//货主类型
                $Model[$k]['FOwnerId'] = $PurchasewarehousingMateriel['fownerid_number'];//货主编码
                $Model[$k]['FSRCID'] = $PurchasewarehousingMateriel['fid'];//行号id
                $Model[$k]['FSRCENTRYID'] = $PurchasewarehousingMateriel['fentryid'];//单据合并
                $Model[$k]['FSTOCKID']= $Storagelocation['fnumber'];//仓库名称
                $Model[$k]['FGIVEAWAY'] = 'false';//赠品

                InventoryService::decInventory(
                    $PurchasewarehousingMateriel['fownerid_number'],
                    $Purchasewdata['returnnumber'],
                    $Purchasereturn['id'],
                    InvTransDocType::PURCHASE_RECEIPT_RETURN_TISSUE->value,
                    $PurchasewarehousingMateriel['fmaterialid'],
                    $Storagelocation['warehousecode'],
                    $v['barcode'],
                    $v['quantityreturned'],
                    $PurchasewarehousingMateriel['fpurchaseorgid_number']
                );

                // 组织间退货 -》生成销售退货表数据
                // Salesreturn  SalesreturnAttached  SalesoutAttached  Salesout  SalesoutTiaoma
                
               $dataresdata = SalesoutAttached::select('salesout_id','id','fmaterialid','fmaterialname','fmaterialmodel')
                // ->join('salesout as salesout', 'salesout.id', '=', 'salesout_attached.salesout_id')
                ->where('salesout_id',$Salesout_fbillno['id'])
                ->where('fmaterialid',$PurchasewarehousingMateriel['fmaterialid'])
                ->where('fmaterialname',$PurchasewarehousingMateriel['fmaterialname'])
                ->where('fmaterialmodel',$PurchasewarehousingMateriel['fmaterialmodel'])
                ->first();
                
                if(empty($dataresdata)){
                    return  throw new FailedException('亲，审核失败，无法获取销售单号物料信息哦');
                }
                $salesreturn_attached[$k]['salesreturn_id'] =  $Salesreturn_id;
                $salesreturn_attached[$k]['salesout_id'] =  $dataresdata['salesout_id'];
                $salesreturn_attached[$k]['salesout_attached_id'] =  $dataresdata['id'];
            }
            
            $SalesreturnAttached_data = SalesreturnAttached::insert($salesreturn_attached);  
            if(empty($SalesreturnAttached_data)){ return  throw new FailedException('亲，审核失败，无法生成销售退货单');}

            //更新状态
            Purchasereturn::query()->updateOrCreate(['id' => $Purchasereturn['id']], [
                'state' => 1,
                'writestate' => 1,
            ]);  

            $FEntity = [];
            foreach($Model as $k=>$v){
                $FEntity[$v['FORGID']][$k]['FSRCSEQ'] = $v['FSRCSEQ'];
                $FEntity[$v['FORGID']][$k]['FMATERIALID'] = $v['FMATERIALID'];
                $FEntity[$v['FORGID']][$k]['FUNITID'] = $v['FUNITID'];
                $FEntity[$v['FORGID']][$k]['FQTY'] = $v['FQTY'];
                $FEntity[$v['FORGID']][$k]['FSTOCKID'] = $v['FSTOCKID'];
                $FEntity[$v['FORGID']][$k]['FGIVEAWAY'] = $v['FGIVEAWAY'];
                $FEntity[$v['FORGID']][$k]['FSRCBILLNO'] = $v['FSRCBILLNO'];
                $FEntity[$v['FORGID']][$k]['FOwnerTypeId'] = $v['FOwnerTypeId'];
                $FEntity[$v['FORGID']][$k]['FOwnerId'] = $v['FOwnerId'];
            }

            foreach($FEntity as $k=>$v){
                $order = [
                    'FID'=>0,
                    'FORGID'=>$k,//组织（传编码）
                    'FBillNo'=>$Purchasewdata['returnnumber'],
                    'FDATE'=>date('Y-m-d H:i:s',time()),
                    'FBILLTYPEID'=>"PUR_MRB",
                    //'FSRCBILLNO'=>$k,
                    'FEntity'=>$v,
                ];
                //金蝶推送
                 (new KingDeeService())->form('TVJB_DJWMSDJ')->invokeSave($order);
            }


   
            DB::commit();

            return ['code'=>1000,'message'=>'添加成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('数据添加失败，服务器上火星了请联系技术处理');
        }

    }






}
